﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QJY.Common;
using QJY.Data;
using Senparc.NeuChar.Entities;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace QJY.API
{
    public class FORMBIManage
    {


        #region 草稿管理
        //获取草稿
        public void GETDRAFT(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            var dt = new SZHL_DRAFTB().Db.Queryable<SZHL_DRAFT>().Where(d => d.CRUser == UserInfo.User.UserName && d.FormCode == P1 && d.DataID == null).WhereIF(!string.IsNullOrEmpty(P2), d => d.FormID == P2).OrderBy(d => d.CRTime, OrderByType.Desc).Take(5).ToList();
            msg.Result = dt;
        }
        public void GETDRAFTMODEL(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int ID = Int32.Parse(P1);
            new SZHL_DRAFTB().GetEntity(p => p.ID == ID && p.ComId == UserInfo.User.ComId && p.CRUser == UserInfo.User.CRUser);
        }

        public void SAVEDRAFT(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            SZHL_DRAFT tt = JsonConvert.DeserializeObject<SZHL_DRAFT>(P1);
            tt.ID = 0;
            if (tt.ID == 0)
            {
                tt.ComId = UserInfo.User.ComId;
                tt.CRUser = UserInfo.User.UserName;
                tt.CRTime = DateTime.Now;
                new SZHL_DRAFTB().Insert(tt);
            }

            msg.Result = tt;
        }
        public void DELDRAFT(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int ID = Int32.Parse(P1);
            new SZHL_DRAFTB().Delete(p => p.ID == ID && p.ComId == UserInfo.User.ComId && p.CRUser == UserInfo.User.UserName);
        }
        #endregion

        #region 流程设置相关

        /// <summary>
        /// 获取流程列表 P1==""流程设置列表，P1!="" 自定义流程添加选择列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETWFPDLIST(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            if (P1 == "SQ")
            {
                //授权管理用户，角色能看到的表单数据
                int lcs = int.Parse(P1);
                string strSql = string.Format(@"SELECT * from Yan_WF_PD  where   lcstatus='{0}' and ComId={1} and  IsSuspended= 'Y'  and " + SqlHelp.concat("','+ManageUser+','") + " like '%,{2},%'", lcs, UserInfo.User.ComId, UserInfo.User.UserName);

                string strRoleSQL = "";
                foreach (var item in UserInfo.UserRoleCode.Split(','))
                {
                    strRoleSQL = strRoleSQL + string.Format(@"SELECT * from Yan_WF_PD  where   lcstatus='{0}' and ComId={1} and  IsSuspended= 'Y'  and  " + SqlHelp.concat("','+ManageRole+','") + "  like '%,{2},%'", lcs, UserInfo.User.ComId, item);
                    strRoleSQL = strRoleSQL + "  UNION  ";
                }
                if (strRoleSQL.Length > 5)
                {
                    strRoleSQL = strRoleSQL.TrimEnd();
                    strRoleSQL = strRoleSQL.Substring(0, strRoleSQL.Length - 5);
                    strSql = strSql + " UNION " + strRoleSQL;
                }
                DataTable dtData = new Yan_WF_PDB().GetDTByCommand(strSql);
                msg.Result = dtData;

            }
            else
            {
                //授权管理用户能看到的表单模板
                string strWhere = "  wfpd.ComId=" + UserInfo.User.ComId;
                string strContent = context.Request("Content") ?? "";
                strContent = strContent.TrimEnd();
                if (strContent != "")
                {
                    strWhere += string.Format(" And ( wfpd.ProcessName like '%{0}%' )", strContent);
                }
                string strLB = context.Request("LB") ?? "";
                strLB = strLB.TrimEnd();
                if (strLB != "")
                {
                    strWhere += string.Format(" And ( wfpd.ProcessClass like '%{0}%' )", strLB);
                }
                string strSql = string.Format(@"SELECT DISTINCT wfpd.ProcessClass, wfpd.ProcessName,wfpd.ManageUser,wfpd.ID,count(wfpi.ID) formCount,wfpd.lcstatus,wfpd.IsSuspended from Yan_WF_PD wfpd LEFT join Yan_WF_PI wfpi on wfpd.ID=wfpi.PDID where   wfpd.isTemp='1' and  {0} group by  wfpd.ProcessClass, wfpd.ProcessName,wfpd.ID,wfpd.lcstatus,wfpd.IsSuspended,wfpd.ManageUser", strWhere, UserInfo.User.UserName);
                msg.Result = new Yan_WF_PDB().GetDTByCommand(strSql);
            }
        }

        /// <summary>
        /// 获取流程的具体步骤
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETTDLIST(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int Id = int.Parse(P1);
            msg.Result = new Yan_WF_TDB().GetEntities(d => d.ProcessDefinitionID == Id).OrderBy(d => d.Taskorder);
        }
        /// <summary>
        /// 流程审批添加
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void ADDPROCESS(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            Yan_WF_PD lcsp = JsonConvert.DeserializeObject<Yan_WF_PD>(P1);
            if (lcsp.ProcessName.Trim() == "")
            {
                msg.ErrorMsg = "流程名称不能为空";
                return;
            }
            if (lcsp.ID == 0)//如果Id为0，为添加操作
            {
                if (new Yan_WF_PDB().GetEntities(d => d.ComId == UserInfo.User.ComId && d.ProcessName == lcsp.ProcessName).Count() > 0)
                {
                    msg.ErrorMsg = "已存在此流程";
                    return;
                }

                lcsp.lcstatus = 1;
                lcsp.ComId = UserInfo.User.ComId;
                if (lcsp.ManageRole != null)
                {
                    lcsp.ManageRole.Trim(',');
                }
                lcsp.CRDate = DateTime.Now;
                lcsp.CRUser = UserInfo.User.UserName;
                lcsp.CRUserName = UserInfo.User.UserRealName;

                new Yan_WF_PDB().Insert(lcsp); //添加流程表数据
            }
            else
            {
                //修改流程表数据
                new Yan_WF_PDB().Update(lcsp);
            }
            //如果流程类型为固定流程并且固定流程内容不为空，添加固定流程数据
            if (lcsp.ProcessType == "1" && !string.IsNullOrEmpty(P2))
            {
                List<Yan_WF_TD> tdList = JsonConvert.DeserializeObject<List<Yan_WF_TD>>(P2);
                tdList.ForEach(d => d.ProcessDefinitionID = lcsp.ID);
                tdList.ForEach(d => d.ComId = UserInfo.User.ComId);
                tdList.ForEach(d => d.CRDate = DateTime.Now);
                tdList.ForEach(d => d.CRUser = UserInfo.User.UserName);
                tdList.ForEach(d => d.TDCODE = d.ProcessDefinitionID + "-" + d.Taskorder);
                tdList.ForEach(d => d.AssignedRole = d.AssignedRole.Trim(','));
                new Yan_WF_TDB().Delete(d => d.ProcessDefinitionID == tdList[0].ProcessDefinitionID);

                List<string> ExtendModes = new List<string>();

                ExtendModes = new JH_Auth_ExtendModeB().GetEntities(D => D.ComId == UserInfo.User.ComId && D.PDID == lcsp.ID).Select(D => D.TableFiledColumn).ToList();
                tdList[0].WritableFields = ExtendModes.ListTOString(',');
                new Yan_WF_TDB().Insert(tdList);

            }
            msg.Result = lcsp;
        }
        /// <summary>
        /// 获取流程信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETPROCESSBYID(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int Id = int.Parse(P1);
            Yan_WF_PD PD = new Yan_WF_PDB().GetEntity(d => d.ID == Id && d.ComId == UserInfo.User.ComId);
            if (PD != null)
            {
                msg.Result = PD;
            }

        }
        /// <summary>
        /// 删除流程信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void DELPROCESSBYID(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            try
            {

                if (new Yan_WF_PDB().Delete(d => d.ID.ToString() == P1))
                {
                    msg.ErrorMsg = "";
                }
            }
            catch (Exception ex)
            {
                msg.ErrorMsg = ex.Message;
            }
        }


        /// <summary>
        /// 禁用或启用流程审批类别
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void MODIFYLCSTATE(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            try
            {
                string strSQL = string.Format("Update Yan_WF_PD set IsSuspended='{0}' where Id={1}", P1, P2);
                new Yan_WF_PDB().ExsSql(strSQL);
            }
            catch (Exception ex)
            {
                msg.ErrorMsg = ex.Message;
            }
        }





        /// <summary>
        /// 获取流程类别数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETLCBDLB(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strSql = string.Format(" SELECT DISTINCT ProcessClass FROM  Yan_WF_PD WHERE  ( CRUser='" + UserInfo.User.UserName + "' OR  SQUser='" + UserInfo.User.UserName + "') and ComId={0} and ProcessClass!='' and ProcessClass is not null  ", UserInfo.User.ComId);
            msg.Result = new Yan_WF_PDB().GetDTByCommand(strSql);
            msg.Result1 = new JH_Auth_RoleB().GetALLEntities();

        }


        #endregion




        #region 流程管理相关


        //待审核统计
        public void GETMODELDSHQTY(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            msg.Result = new Yan_WF_PIB().GetDSH(UserInfo.User).Count;

        }



        /// <summary>
        /// 获取流程数据添加页面
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETWFDATA(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            try
            {
                int PDID = int.Parse(P1);
                if (PDID > 0)
                {
                    Yan_WF_PD pdmodel = new Yan_WF_PDB().GetEntity(d => d.ID == PDID);
                    if (pdmodel != null)
                    {
                        var dtList = new Yan_WF_TDB().GetEntities(d => d.ProcessDefinitionID == pdmodel.ID).OrderBy(d => d.Taskorder);
                        msg.Result = dtList;
                        msg.Result1 = pdmodel;
                    }

                }
            }
            catch (Exception ex)
            {
                msg.ErrorMsg = ex.Message;
            }
        }



        public void GETMANGWFDATA(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            try
            {
                int PIID = int.Parse(P1);
                if (PIID > 0)
                {
                    Yan_WF_PI PIMODEL = new Yan_WF_PIB().GetEntity(d => d.ID == PIID);

                    if (PIMODEL == null)
                    {
                        msg.ErrorMsg = "流程数据已清除";
                        return;
                    }
                    else
                    {
                        DataTable dtList = new Yan_WF_TDB().GetEntities(d => d.ProcessDefinitionID == PIMODEL.PDID.Value).OrderBy(d => d.Taskorder).ToDataTable();
                        dtList.Columns.Add("EndTime");
                        dtList.Columns.Add("state");
                        dtList.Columns.Add("TIData", Type.GetType("System.Object"));
                        dtList.Columns.Add("RBData", Type.GetType("System.Object"));



                        foreach (DataRow dr in dtList.Rows)
                        {
                            string tdCode = dr["TDCODE"].ToString();

                            List<Yan_WF_TI> tiModelSALL = new Yan_WF_TIB().GetEntities(d => d.PIID == PIID && d.TDCODE == tdCode).ToList();//
                            List<Yan_WF_TI> tiModelS = tiModelSALL.Where(d => d.EndTime != null).OrderByDescending(D => D.EndTime).ToList();//
                            tiModelS.ForEach(d => d.zhuandanto = new JH_Auth_UserB().GetUserRealName(UserInfo.User.ComId.Value, d.TaskUserID));

                            if (tiModelS.Count > 0)
                            {
                                dr["EndTime"] = tiModelS[0].EndTime;
                                dr["TIData"] = tiModelS;
                                if (tiModelS.Where(D => D.TaskState == -1).Count() > 0)
                                {
                                    dr["state"] = "-1";
                                }
                                else
                                {
                                    dr["state"] = "1";
                                }
                            }
                            if (dr["AboutAttached"].ToString() == "1" && tiModelSALL.Count != tiModelS.Count)//会签并且有任务未结束,改节点结束时间设为空
                            {
                                dr["EndTime"] = "";
                            }

                            List<Yan_WF_ChiTask> tiChiS = new Yan_WF_ChiTaskB().GetEntities(d => d.Remark == PIID.ToString() && d.TaskInstanceID == tdCode).OrderByDescending(D => D.Crdate).ToList();//
                            dr["RBData"] = tiChiS;//子任务数据(退回上一步,转审)



                        }
                        msg.Result = dtList;

                        Yan_WF_PD pdmodel = new Yan_WF_PDB().GetEntity(d => d.ID == PIMODEL.PDID);
                        msg.Result1 = pdmodel;
                        msg.Result2 = "{ \"ISCANSP\":\"" + new Yan_WF_PIB().isCanSP(UserInfo.User.UserName, int.Parse(P1)) + "\",\"ISCANCEL\":\"" + new Yan_WF_PIB().isCanCancel(UserInfo.User.UserName, PIMODEL, UserInfo.UserBMQXCode) + "\"}";
                        msg.Result3 = PIMODEL;//可修改字段
                        msg.Result5 = new Yan_WF_PIB().GetPITaskOrder(PIMODEL.ID);
                    }
                    decimal Remark = 0;
                    decimal.TryParse(PIMODEL.Remark1, out Remark);
                    PIMODEL.Remark1 = decimal.ToInt32(Remark + 1).ToString();
                    new Yan_WF_PIB().Update(PIMODEL);
                }
            }
            catch (Exception ex)
            {
                msg.ErrorMsg = ex.Message;
            }
        }


        /// <summary>
        /// 删除流程及表单相关数据（按照流程ID删除数据）
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void CANCELWF(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            foreach (var ID in P1.Split(','))
            {
                int PIID = 0;
                if (!int.TryParse(ID, out PIID))
                {
                    msg.ErrorMsg = "数据错误";
                    return;
                }
                string strRoleName = new JH_Auth_UserRoleB().GetRoleNameByUserName(UserInfo.User.UserName, UserInfo.User.ComId.Value);
                //管理员可以强制删除
                string strReturn = new Yan_WF_PIB().CanCancel(PIID, UserInfo.User.UserName, UserInfo.UserBMQXCode, strRoleName.Contains("管理员") ? "Y" : "N");
                if (strReturn != "")
                {
                    msg.ErrorMsg = strReturn;
                }
            }


        }

        /// <summary>
        /// 删除流程及表单相关数据（按照数据ID删除数据）
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void DELWFDATA(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            string dataids = P2;
            foreach (int pid in dataids.SplitTOInt(','))
            {
                new Yan_WF_PIB().CanCancel(pid, UserInfo.User.UserName, UserInfo.UserBMQXCode);
            }

        }


        /// <summary>
        /// 对流程待处理人员发送提醒（催办）
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void SENDLCCB(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int Id = int.Parse(P1);
            var CBResult = new Yan_WF_TIB().GetEntities(d => d.PIID == Id && d.TaskState == 0);
            foreach (Yan_WF_TI item in CBResult)
            {
                SZHL_TXSX MODEL = new SZHL_TXSXB().GetEntity(d => d.TXUser == item.TaskUserID && d.intProcessStanceid == item.PIID);
                if (MODEL != null)
                {
                    MODEL.Status = "0";
                    new SZHL_TXSXB().Update(MODEL);
                }
            }
        }

        public void MANAGEWF(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            try
            {
                string strZShUser = context.Request("zsr") ?? "";
                string strCSUser = context.Request("csr") ?? "";
                string modelcode = context.Request("formcode") ?? "";
                string strContent = context.Request("content") ?? "";

                int PID = int.Parse(P1);




                Yan_WF_PIB PIB = new Yan_WF_PIB();
                if (PIB.isCanSP(UserInfo.User.UserName, PID) == "Y")//先判断用户能不能处理此流程
                {

                    List<string> ListNextUser = new List<string>();
                    string isTDComplete = "N";//td是否完成
                    string isSaveData = "N";//是否需要更新表单

                    Yan_WF_PI PI = PIB.GetEntity(d => d.ID == PID);
                    //更新抄送人
                    string strOLDContent = PI.Content;

                    PI.ChaoSongUser = strCSUser;
                    PI.Content = strContent;//更新表单数据
                    PIB.Update(PI);
                    //更新抄送人


                    PIB.MANAGEWF(UserInfo.User.UserName, PI, P2, ref ListNextUser, ref isTDComplete, ref isSaveData, strZShUser);//处理任务

                    if (isSaveData != "Y")//没办法,不得不这样搞,处理流程管理人员时需要及时更新Content的问题
                    {
                        PI.Content = strOLDContent;
                    }
                    PIB.Update(PI);

                    //当前节点结束时
                    Yan_WF_PD PD = new Yan_WF_PDB().GetEntity(d => d.ID == PI.PDID.Value);
                    if (isTDComplete == "Y")
                    {


                        string content = GetLCMsg(PI, PD.ProcessName, "1", PI.CRUserName);
                        string strTXUser = ListNextUser.ListTOString(',');
                        string funName = "LCSPCHECK";
                        //添加消息提醒
                        string strIsComplete = ListNextUser.Count() == 0 ? "Y" : "N";//结束流程,找不到人了
                        if (strIsComplete == "Y")//找不到下家并且该TD结束就结束流程,并且给流程发起人发送消息
                        {
                            PIB.ENDWF(PID);
                            msg.Result = "Y";//已结束
                            SAVEEXDATA(context, msg, PID.ToString(), PI.PDID.Value.ToString(), UserInfo);//更新扩展数据
                            content = GetLCMsg(PI, PD.ProcessName, "2", UserInfo.User.UserRealName);
                            strTXUser = PI.CRUser;
                            //发送消息给抄送人 
                            if (!string.IsNullOrEmpty(PI.ChaoSongUser))
                            {
                                SZHL_TXSX CSTX = new SZHL_TXSX();
                                CSTX.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                CSTX.APIName = "FORMBI";
                                CSTX.ComId = UserInfo.User.ComId;
                                CSTX.FunName = "LCSPCHECK";
                                CSTX.intProcessStanceid = PID;
                                CSTX.CRUserRealName = UserInfo.User.UserRealName;
                                CSTX.MsgID = PID.ToString();
                                CSTX.TXContent = GetLCMsg(PI, PD.ProcessName, "3", PI.CRUserName);
                                CSTX.ISCS = "Y";
                                CSTX.TXUser = PI.ChaoSongUser;
                                CSTX.TXMode = modelcode;
                                CSTX.CRUser = UserInfo.User.UserName;
                                TXSXAPI.AddALERT(CSTX); //时间为发送时间
                            }
                        }
                        SZHL_TXSX TX = new SZHL_TXSX();
                        TX.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        TX.APIName = "FORMBI";
                        TX.ComId = UserInfo.User.ComId;
                        TX.FunName = funName;
                        TX.intProcessStanceid = PID;
                        TX.CRUser = PI.CRUser;
                        TX.CRUserRealName = UserInfo.User.UserRealName;
                        TX.MsgID = PID.ToString();
                        TX.TXContent = content;
                        TX.TXUser = strTXUser;
                        TX.TXMode = modelcode;
                        TXSXAPI.AddALERT(TX); //时间为发送时间
                    }

                    if (!string.IsNullOrEmpty(strZShUser))
                    {
                        SZHL_TXSX TX = new SZHL_TXSX();
                        TX.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        TX.APIName = "FORMBI";
                        TX.ComId = UserInfo.User.ComId;
                        TX.FunName = "LCSPCHECK";
                        TX.intProcessStanceid = PID;
                        TX.CRUser = PI.CRUser;
                        TX.CRUserRealName = UserInfo.User.UserRealName;
                        TX.MsgID = PID.ToString();
                        TX.TXContent = GetLCMsg(PI, PD.ProcessName, "4", UserInfo.User.UserRealName);
                        TX.TXUser = strZShUser;
                        TX.TXMode = modelcode;
                        TXSXAPI.AddALERT(TX); //时间为发送时间
                    }


                }
                else
                {
                    msg.ErrorMsg = "该流程已被处理,您已无法处理此流程";
                }

            }
            catch (Exception ex)
            {
                msg.ErrorMsg = ex.Message;
            }
        }




        /// <summary>
        /// 退回当前流程
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void REBACKWF(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            try
            {
                int PID = int.Parse(P1);
                Yan_WF_PIB PIB = new Yan_WF_PIB();
                string strContent = "";
                string TXUser = UserInfo.User.UserName;
                Yan_WF_PI PI = new Yan_WF_PIB().GetEntity(d => d.ID == PID);

                if (PIB.isCanSP(UserInfo.User.UserName, PID) == "Y")//先判断用户能不能处理此流程
                {
                    string cantype = context.Request("cantype") ?? "0";//退回类型
                    if (cantype == "0")
                    {
                        new Yan_WF_PIB().REBACKLC(UserInfo.User.UserName, PID, P2);//结束任务
                        strContent = GetLCMsg(PI, new Yan_WF_PDB().GetEntity(d => d.ID == PI.PDID.Value).ProcessName, "5", UserInfo.User.UserRealName);
                        TXUser = PI.CRUser;
                    }
                    else
                    {
                        new Yan_WF_PIB().REBACKPREWF(UserInfo.User.UserName, PID, P2, ref TXUser);//退到上一步
                        strContent = GetLCMsg(PI, new Yan_WF_PDB().GetEntity(d => d.ID == PI.PDID.Value).ProcessName, "5", UserInfo.User.UserRealName);

                    }
                    string ModeCode = context.Request("formcode") ?? "LCSP";

                    if (!string.IsNullOrEmpty(ModeCode))
                    {


                        //消息提醒
                        SZHL_TXSX TX = new SZHL_TXSX();
                        TX.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        TX.APIName = "FORMBI";
                        TX.ComId = UserInfo.User.ComId;
                        TX.FunName = "LCSPCHECK";
                        TX.intProcessStanceid = PID;
                        TX.CRUserRealName = UserInfo.User.UserRealName;
                        TX.MsgID = PID.ToString();
                        TX.TXContent = GetLCMsg(PI, new Yan_WF_PDB().GetEntity(d => d.ID == PI.PDID.Value).ProcessName, "5", UserInfo.User.UserRealName);
                        TX.TXUser = TXUser;
                        TX.TXMode = ModeCode;
                        TX.CRUser = UserInfo.User.UserName;
                        TXSXAPI.AddALERT(TX); //时间为发送时间
                    }
                }
                else
                {
                    msg.ErrorMsg = "该流程已被处理,您已无法处理此流程";
                }





            }
            catch (Exception ex)
            {
                msg.ErrorMsg = ex.Message;
            }
        }




        /// <summary>
        /// 为没有流程得表单数据批量生成流程
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GENWF(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            try
            {
                int PDID = 0;
                int.TryParse(P1, out PDID);
                Yan_WF_PD PD = new Yan_WF_PDB().GetEntity(d => d.ID == PDID && d.ComId == UserInfo.User.ComId);

                DataTable dt = new Yan_WF_PDB().GetDTByCommand("SELECT * FROM " + PD.RelatedTable + " WHERE intProcessStanceid='0'");

                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    JArray gldata = (JArray)JsonConvert.DeserializeObject(PD.Tempcontent);
                    foreach (JObject pro in gldata)
                    {

                        string glfield = (string)pro["glfiled"];
                        if (!string.IsNullOrEmpty(glfield))
                        {
                            pro["value"] = dt.Rows[i][glfield].ToString();
                        }

                        string strglfiled1 = (string)pro["glfiled1"] ?? "";
                        if (!string.IsNullOrEmpty(strglfiled1))
                        {
                            pro["valuetext"] = dt.Rows[i][strglfiled1].ToString();
                        }


                        JObject chi = (JObject)pro["childpro"];
                        if (!string.IsNullOrEmpty(glfield))
                        {
                            if (chi.Property("svalue") != null)
                            {
                                chi["svalue"] = dt.Rows[i][glfield].ToString();
                            }
                            if (chi.Property("mvalue") != null)
                            {
                                JArray arrmvalue = JArray.FromObject(dt.Rows[i][glfield].ToString().Split(','));
                                chi["mvalue"] = arrmvalue;

                                //  dt.Rows[i][glfield].ToString().Split(",")
                            }
                        }


                    }
                    string strTemp = JsonConvert.SerializeObject(gldata);
                    string strUser = dt.Rows[i]["CRUser"].ToString();
                    string id = dt.Rows[i]["ID"].ToString();

                    string strCRUserName = new JH_Auth_UserB().GetUserRealName(UserInfo.User.ComId.Value, strUser);
                    Yan_WF_PIB PIB = new Yan_WF_PIB();
                    List<string> ListNextUser = new List<string>();//获取下一任务的处理人
                    Yan_WF_PI PI = new Yan_WF_PI();
                    PI.CRUserName = strCRUserName;
                    PI.BranchName = "";
                    PI.BranchNO = 0;
                    PI.Content = strTemp;
                    PI.PDID = PD.ID;
                    PI.WFFormNum = new Yan_WF_PIB().CreateWFNum(PI.PDID.ToString());
                    PI.ComId = PD.ComId;
                    PI.StartTime = DateTime.Parse(dt.Rows[i]["CRDate"].ToString());
                    PI.CRUser = strUser;
                    PI.CRDate = DateTime.Parse(dt.Rows[i]["CRDate"].ToString());
                    PI.PITYPE = "-1";
                    PI.ChaoSongUser = "";
                    PI.Description = PD.ProcessName;
                    PI.isGD = "N";
                    PI.isComplete = "Y";
                    PI.CompleteTime = DateTime.Now;
                    new Yan_WF_PIB().Insert(PI);
                    Yan_WF_TI TI = PIB.StartWF(PD, "", UserInfo.User.UserName, "", "", PI, ref ListNextUser);
                    new Yan_WF_PDB().ExsSql(" UPDATE " + PD.RelatedTable + " SET   intProcessStanceid='" + PI.ID + "' WHERE ID='" + id + "'");



                }
                //返回新增的任务
                msg.Result = dt;

            }
            catch (Exception ex)
            {
                msg.ErrorMsg = ex.Message;
            }
        }

        /// <summary>
        /// 开始流程
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">启动流程的应用Code</param>
        /// <param name="P2">审核人信息</param>
        /// <param name="UserInfo"></param>
        public void STARTWF(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            try
            {
                string strModelCode = P1;
                string strCSR = context.Request("csr") ?? "";
                string strZSR = context.Request("zsr") ?? "";
                string strContent = context.Request("content") ?? "";



                int PDID = 0;
                int.TryParse(context.Request("PDID") ?? "0", out PDID);
                Yan_WF_PD PD = new Yan_WF_PDB().GetEntity(d => d.ID == PDID && d.ComId == UserInfo.User.ComId);

                if (PD == null)
                {
                    //没有流程,直接返回
                    return;
                }
                Yan_WF_PIB PIB = new Yan_WF_PIB();
                List<string> ListNextUser = new List<string>();//获取下一任务的处理人
                Yan_WF_PI PI = new Yan_WF_PI();
                PI.CRUserName = UserInfo.User.UserRealName;
                PI.BranchName = UserInfo.BranchInfo.DeptName;
                PI.BranchNO = UserInfo.BranchInfo.DeptCode;
                PI.Content = strContent;
                PI.PDID = PD.ID;
                PI.WFFormNum = new Yan_WF_PIB().CreateWFNum(PI.PDID.ToString());
                PI.ComId = PD.ComId;
                PI.StartTime = DateTime.Now;
                PI.CRUser = UserInfo.User.UserName;
                PI.CRDate = DateTime.Now;
                PI.PITYPE = PD.ProcessType;
                PI.ChaoSongUser = strCSR;
                PI.isGD = "N";
                new Yan_WF_PIB().Insert(PI);



                Yan_WF_TI TI = PIB.StartWF(PD, strModelCode, UserInfo.User.UserName, strZSR, strCSR, PI, ref ListNextUser);

                //返回新增的任务
                msg.Result = PI;
                msg.Result1 = TI;


                //发送消息给审核人员
                string jsr = ListNextUser.ListTOString(',');
                if (!string.IsNullOrEmpty(jsr))
                {
                    SZHL_TXSX TX = new SZHL_TXSX();
                    TX.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    TX.APIName = "FORMBI";
                    TX.ComId = UserInfo.User.ComId;
                    TX.FunName = "LCSPCHECK";
                    TX.intProcessStanceid = TI.PIID;
                    TX.CRUserRealName = UserInfo.User.UserRealName;
                    TX.MsgID = TI.PIID.ToString();
                    TX.TXContent = GetLCMsg(PI, PD.ProcessName, "0", PI.CRUserName);
                    TX.TXUser = jsr;
                    TX.TXMode = strModelCode;
                    TX.CRUser = UserInfo.User.UserName;
                    TXSXAPI.AddALERT(TX); //时间为发送时间
                }
                //发送消息
            }
            catch (Exception ex)
            {
                msg.ErrorMsg = ex.Message;
            }
        }


        public void SAVEPIDATA(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int pId = int.Parse(P1);
            Yan_WF_PI PI = new Yan_WF_PIB().GetEntity(d => d.ID == pId);

            string strRoleName = new JH_Auth_UserRoleB().GetRoleNameByUserName(UserInfo.User.UserName, UserInfo.User.ComId.Value);
            //管理员可以更新表单
            if (new Yan_WF_PIB().isCanCancel(UserInfo.User.UserName, PI, UserInfo.UserBMQXCode) == "Y" || strRoleName.Contains("管理员"))
            {
                //更新抄送人
                PI.Content = P2;
                new Yan_WF_PIB().Update(PI);
                if (PI.PITYPE == "-1" || strRoleName.Contains("管理员"))
                {
                    SAVEEXDATA(context, msg, PI.ID.ToString(), PI.PDID.Value.ToString(), UserInfo);//更新扩展数据
                }
            }
            else
            {
                msg.ErrorMsg = "没有权限进行此操作";
            }


        }


        /// <summary>
        /// 获取新增单据得流水号(可能存在跳号)
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void CRWFNUM(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string pdId = P1;
            string strQZ = P2;

            if (pdId == "257")
            {
                //提案号
                DataTable dtxh = new Yan_WF_PDB().GetDTByCommand("   SELECT ISNULL(taxh, tadm+'000') AS taxh FROM  qj_tatz WHERE ID IN (  SELECT MAX(ID)  FROM qj_tatz  )");
                int taxh = int.Parse(dtxh.Rows[0][0].ToString()) + 1;
                msg.Result = "xh-" + taxh.ToString();
            }
            else
            {
                msg.Result = new Yan_WF_PIB().CreateWFNum(pdId, P2);
            }
        }


        #endregion


        #region 流程中的消息处理方法
        public void LCSPCHECK(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            SZHL_TXSX TX = JsonConvert.DeserializeObject<SZHL_TXSX>(P1);

            //todo 需要根据PID找到对应的数据ID
            Article ar0 = new Article();
            ar0.Title = TX.TXContent;
            ar0.Description = "";
            ar0.Url = TX.MsgID;
            List<Article> al = new List<Article>();
            al.Add(ar0);
            JH_Auth_UserB.UserInfo UserTXInfo = new JH_Auth_UserB().GetUserInfo(TX.ComId.Value, TX.CRUser);
            if (!string.IsNullOrEmpty(TX.TXUser))
            {


                //发送微信消息
                WXHelp wx = new WXHelp(UserTXInfo.QYinfo);
                wx.SendTH(al, TX.TXMode, "A", TX.TXUser);

                if (!string.IsNullOrEmpty(TX.TXContent))
                {
                    //发送PC消息
                    new JH_Auth_User_CenterB().SendMsg(UserTXInfo, TX.TXMode, TX.TXContent, TX.MsgID, TX.TXUser, "A", TX.intProcessStanceid, TX.ISCS);

                    //发送短信
                    string strContent = HttpUtility.UrlEncode(TX.TXContent);

                    string strPhone = new JH_Auth_UserB().GetUserSPhone(TX.TXUser);
                    if (!string.IsNullOrEmpty(strPhone))
                    {
                        CommonHelp.SendDX(strPhone, strContent, "");
                    }

                }


            }

        }


        public string GetLCMsg(Yan_WF_PI PI, string ProcessName, string strMsgType, string strUserRealName)
        {
            string strMSG = "";
            if (PI.PDID != 257)
            {
                if (strMsgType == "0")
                {
                    strMSG = strUserRealName + "发起了" + ProcessName + "，请您查阅审核";

                }
                if (strMsgType == "1")
                {
                    strMSG = strUserRealName + "发起了" + ProcessName + "流程,等待您处理";
                }

                if (strMsgType == "2")
                {
                    strMSG = strUserRealName + "处理完成了您发起的" + ProcessName + "流程";

                }
                if (strMsgType == "3")
                {
                    strMSG = strUserRealName + "抄送一个" + ProcessName + "，请您查阅接收";

                }
                if (strMsgType == "4")
                {
                    strMSG = strUserRealName + "转审了" + ProcessName + "流程,等待您处理";
                }
                if (strMsgType == "5")
                {
                    strMSG = strUserRealName + "退回了" + ProcessName + "，请您查阅";
                }

            }
            else
            {
                string strOrder = new Yan_WF_PIB().GetPITaskOrder(PI.ID);
            }
            return strMSG;


        }
        #endregion


        #region 表单数据相关

        /// <summary>
        /// 流程审批列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETLCSPLIST(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string userName = UserInfo.User.UserName;
            string strWhere = " 1=1 and pi.ComId=" + UserInfo.User.ComId;

            string leibie = context.Request("lb") ?? "";
            if (leibie != "")
            {
                strWhere += string.Format(" And pi.PDID='{0}' ", leibie);
                int pdid = int.Parse(leibie);
                msg.Result2 = new Yan_WF_PDB().GetEntity(d => d.ID == pdid);
            }
            string formname = context.Request("formname") ?? "";
            if (formname != "")
            {
                strWhere += string.Format(" And pd.ProcessName like '%{0}%' ", formname);

            }
            int DataID = -1;
            int.TryParse(context.Request("ID") ?? "-1", out DataID);//记录Id
            if (DataID != -1)
            {
                strWhere += string.Format(" And pi.ID = '{0}'", DataID);
            }

            if (P1 != "")
            {
                int page = 0;
                int pagecount = 8;
                int.TryParse(context.Request("p") ?? "1", out page);
                int.TryParse(context.Request("pagecount") ?? "8", out pagecount);//页数
                page = page == 0 ? 1 : page;
                int total = 0;

                DataTable dt = new DataTable();

                switch (P1)
                {
                    case "1": //创建
                        {
                            strWhere += " And pi.CRUser ='" + userName + "'";
                        }

                        break;
                    case "2": //待审核
                        {
                            List<string> intProD = new Yan_WF_PIB().GetDSH(UserInfo.User).Select(d => d.PIID.ToString()).ToList();
                            if (intProD.Count > 0)
                            {
                                strWhere += " And pi.ID in (" + (intProD.ListTOString(',') == "" ? "0" : intProD.ListTOString(',')) + ")";
                            }
                            else
                            {
                                strWhere += " and 1=0 ";
                            }
                        }
                        break;
                    case "3": //已审核
                        {
                            var intProD = new Yan_WF_PIB().GetYSH(UserInfo.User).Select(d => d.PIID.ToString()).ToList();
                            if (intProD.Count > 0)
                            {
                                strWhere += " And pi.ID  in (" + (intProD.ListTOString(',') == "" ? "0" : intProD.ListTOString(',')) + ")";
                            }
                            else
                            {
                                strWhere += " and 1=0 ";
                            }
                        }
                        break;

                    case "4": //抄送我的
                        {
                            strWhere += " AND pi.isComplete='Y'    AND   ',' + pi.ChaoSongUser  + ',' like '%," + userName + ",%'";

                        }
                        break;
                }
                dt = new Yan_WF_PIB().GetDataPager("Yan_WF_PI pi inner join Yan_WF_PD pd on pd.ID=pi.PDID ", "pi.*,pd.ProcessClass, pd.ProcessType,pd.ProcessName,'LCSP' as ModelCode", pagecount, page, " CRDate desc", strWhere, ref total);
                dt.Columns.Add("StatusName");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int pid = int.Parse(dt.Rows[i]["ID"].ToString());
                    string strStatusName = "正在审批";
                    if (dt.Rows[i]["isComplete"].ToString() == "Y")
                    {
                        strStatusName = "已审批";
                    }
                    if (dt.Rows[i]["IsCanceled"].ToString() == "Y")
                    {
                        strStatusName = "已退回";
                    }
                    if (dt.Rows[i]["ProcessType"].ToString() == "-1")
                    {
                        strStatusName = "无流程数据";
                    }
                    dt.Rows[i]["StatusName"] = strStatusName;
                }
                dt.Columns.Remove("Content");
                msg.Result = dt;
                msg.Result1 = total;
            }
        }


        #endregion

        #region 表单处理

        /// <summary>
        /// 更新表单模板
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void SETPDTEMP(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int Id = 0;
            int.TryParse(P1, out Id);


            string strFormop = context.Request("formop") ?? "";
            string strfmdata = context.Request("fmdata") ?? "";

            Yan_WF_PD PD = new Yan_WF_PDB().GetEntity(d => d.ID == Id && d.ComId == UserInfo.User.ComId);
            PD.Tempcontent = P2.Replace("null", "''");
            PD.Poption = strFormop;
            PD.fmdata = strfmdata;
            JArray filds = JArray.Parse(P2);

            List<JH_Auth_ExtendMode> ListNew = new List<JH_Auth_ExtendMode>();
            foreach (JObject item in filds)
            {
                List<string> ListNofiled = new List<string>() { "qjLine" };
                string strComponentName = (string)item["component"];
                if (!ListNofiled.Contains(strComponentName))
                {
                    //有几个组件是不需要存到字段里得
                    JH_Auth_ExtendMode Model = new JH_Auth_ExtendMode();
                    Model.ComId = UserInfo.User.ComId;
                    Model.CRDate = DateTime.Now;
                    Model.CRUser = UserInfo.User.UserName;
                    Model.PDID = PD.ID;
                    Model.TableFiledColumn = ((string)item["wigdetcode"]).Trim();
                    Model.TableFiledName = ((string)item["title"]).Trim();
                    string strFileType = "Str";
                    if ((string)item["eltype"] == "number")
                    {
                        strFileType = "Num";

                    }
                    if ((string)item["eltype"] == "date" || (string)item["eltype"] == "datetime")
                    {
                        strFileType = "Date";
                    }
                    if ((string)item["eltype"] == "qjTable")
                    {
                        strFileType = "Table";
                    }
                    Model.TableFileType = strFileType;
                    Model.TableName = "LCSP";
                    ListNew.Add(Model);
                }

            }
            new JH_Auth_ExtendModeB().Delete(d => d.PDID == PD.ID);
            new JH_Auth_ExtendModeB().Insert(ListNew);
            new Yan_WF_PDB().Update(PD);
            //保存模板得时候顺便保存扩展字段

        }


        //更新表单得模板Json数据
        public void SAVEJSONDATA(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int Id = 0;
            int.TryParse(P1, out Id);
            Yan_WF_PD PD = new Yan_WF_PDB().GetEntity(d => d.ID == Id && d.ComId == UserInfo.User.ComId);
            PD.Tempcontent = P2;
            new Yan_WF_PDB().Update(PD);
        }



        public void SAVEEXDATA(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int piId = 0;
            int.TryParse(P1, out piId);
            int PDID = 0;
            int.TryParse(P2, out PDID);
            Yan_WF_PI lcsp = new Yan_WF_PIB().GetEntity(d => d.ID == piId);
            Yan_WF_PD pd = new Yan_WF_PDB().GetEntity(d => d.ID == PDID);
            JArray datas = (JArray)JsonConvert.DeserializeObject(lcsp.Content);
            var dt = new Dictionary<string, object>();

            JH_Auth_UserB.UserInfo CUser = new JH_Auth_UserB().GetUserInfo(UserInfo.User.ComId.Value, lcsp.CRUser);
            try
            {
                List<JH_Auth_ExtendData> ListNew = new List<JH_Auth_ExtendData>();
                foreach (JObject item in datas)
                {
                    JH_Auth_ExtendData Model = new JH_Auth_ExtendData();
                    Model.ComId = CUser.User.ComId;
                    Model.DataID = piId;
                    Model.PDID = PDID;
                    Model.TableName = "LCSP";
                    Model.ExFiledColumn = (string)item["wigdetcode"];
                    Model.ExFiledName = (string)item["title"];
                    string strValue = "";
                    strValue = (string)item["value"];
                    Model.ExtendDataValue = strValue.Trim(',');
                    Model.CRUser = CUser.User.UserName;
                    Model.CRDate = DateTime.Now;
                    Model.CRUserName = CUser.User.UserRealName;
                    Model.BranchNo = CUser.BranchInfo.DeptCode;
                    Model.BranchName = CUser.BranchInfo.DeptName;
                    ListNew.Add(Model);

                    string strglfiled = (string)item["glfiled"] ?? "";
                    if (strglfiled != "")
                    {
                        dt.Add(strglfiled, strValue);
                    }

                    string strglfiled1 = (string)item["glfiled1"] ?? "";
                    if (strglfiled1 != "")
                    {
                        string strValueText = "";
                        strValueText = (string)item["valuetext"];
                        dt.Add(strglfiled1, strValueText);
                    }
                }
                new JH_Auth_ExtendDataB().Delete(d => d.DataID == piId && d.PDID == PDID);
                new JH_Auth_ExtendDataB().Insert(ListNew);

                if (!string.IsNullOrEmpty(pd.RelatedTable))
                {
                    DataTable dtr = new Yan_WF_PDB().GetDTByCommand("SELECT id FROM " + pd.RelatedTable + " WHERE intProcessStanceid='" + piId.ToString() + "'");
                    DBFactory db = new BI_DB_SourceB().GetDB(0);
                    if (dtr.Rows.Count > 0)
                    {
                        dt.Add("id", dtr.Rows[0]["id"].ToString());
                        db.UpdateData(dt, pd.RelatedTable);
                        //更新
                    }
                    else
                    {
                        dt.Add("CRUser", CUser.User.UserName);
                        dt.Add("CRDate", DateTime.Now);
                        dt.Add("ComID", CUser.User.ComId.Value);
                        dt.Add("intProcessStanceid", piId);
                        dt.Add("CRUserName", CUser.User.UserRealName);


                        if (!dt.ContainsKey("DCode"))
                        {
                            //管理站特殊处理
                            int BranCode = CUser.User.BranchCode;
                            if (dt.ContainsKey("zid"))
                            {
                                BranCode = int.Parse(dt.Where(D => D.Key == "zid").First().Value.ToString());
                            }
                            dt.Add("DCode", BranCode);
                        }
                        if (!dt.ContainsKey("DName"))
                        {
                            string DeptName = CUser.BranchInfo.DeptName;
                            if (dt.ContainsKey("zname"))
                            {
                                DeptName = dt.Where(D => D.Key == "zname").First().Value.ToString();
                            }
                            dt.Add("DName", DeptName);
                        }

                        //新增
                        db.InserData(dt, pd.RelatedTable);
                    }
                }

            }
            catch (Exception ex)
            {
                CommonHelp.WriteLOG(ex.Message.ToString());

            }



        }
        public void GETSQLDATA(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dt = new DataTable();
            string SQL = CommonHelp.Filter(P1);
            dt = new Yan_WF_PDB().GetDTByCommand(SQL);
            msg.Result = dt;
        }

        /// <summary>
        /// 获取表单内的可管理字段
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETFORMFILED(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int pdid = 0;
            int.TryParse(P1, out pdid);
            int tdid = 0;
            int.TryParse(P2, out tdid);
            List<JH_Auth_ExtendMode> ExtendModes = new List<JH_Auth_ExtendMode>();
            ExtendModes = new JH_Auth_ExtendModeB().GetEntities(D => D.ComId == UserInfo.User.ComId && D.PDID == pdid).ToList();
            msg.Result = ExtendModes;

            if (tdid != 0)
            {
                Yan_WF_TD TD = new Yan_WF_TDB().GetEntity(d => d.ID == tdid && d.ComId == UserInfo.User.ComId);
                msg.Result1 = TD.WritableFields;//可编辑
                msg.Result2 = TD.ReadableFields;//可见字段
                msg.Result3 = TD;
            }


        }

        /// <summary>
        /// 更新表单可管理字段
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void SETPDFILED(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int Id = 0;
            int.TryParse(P1, out Id);
            string hidfid = context.Request("hidfid") ?? "";
            string formdata = context.Request("form") ?? "";



            Yan_WF_TD TD = new Yan_WF_TDB().GetEntity(d => d.ID == Id && d.ComId == UserInfo.User.ComId);
            TD.WritableFields = P2;
            TD.ReadableFields = hidfid;
            TD.isCanEdit = formdata;
            new Yan_WF_TDB().Update(TD);
        }




        /// <summary>
        /// 归档表单
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GDFORM(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            P2 = (P2 == "" ? "N" : P2);
            if (!string.IsNullOrEmpty(P1))
            {
                new Yan_WF_PIB().GDForm(P2, UserInfo.User.ComId.Value, P1);
            }
        }

        /// <summary>
        /// 彻底删除已归档的数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void DELFORM(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            if (!string.IsNullOrEmpty(P1))
            {
                int[] IDS = P1.SplitTOInt(',');
                new Yan_WF_PIB().Delete(d => d.ComId == UserInfo.User.ComId && IDS.Contains(d.ID));
                new Yan_WF_TIB().Delete(d => d.ComId == UserInfo.User.ComId && IDS.Contains(d.PIID));
                new JH_Auth_ExtendDataB().Delete(d => d.ComId == UserInfo.User.ComId && IDS.Contains(d.DataID.Value));
                //是不是还需要删除关联表得数据
            }
        }


        #endregion

        #region 表单统计
        public void GETBDTJDATA(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int pdid = 0;
            int.TryParse(P1, out pdid);


            string strSDate = context.Request("sdate") ?? DateTime.Now.AddYears(-20).ToString("yyyy-MM-dd");
            string strEDate = context.Request("edate") ?? DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");


            List<JH_Auth_ExtendMode> ExtendModes = new List<JH_Auth_ExtendMode>();
            ExtendModes = new JH_Auth_ExtendModeB().GetEntities(D => D.ComId == UserInfo.User.ComId && D.PDID == pdid).ToList();
            string strWhere = "";
            if (P2 != "")
            {
                JArray datas = (JArray)JsonConvert.DeserializeObject(P2);
                foreach (JObject item in datas)
                {
                    string filed = (string)item["filed"];
                    if (ExtendModes.Select(D => D.TableFiledColumn).ToList().Contains(filed))
                    {
                        string qtype = (string)item["qtype"];
                        string qvalue = (string)item["qvalue"];
                        strWhere = CommonHelp.CreateqQsql(filed, qtype, qvalue);
                    }

                }
            }
            string strISGD = context.Request("isGD") ?? "";
            if (strISGD != "")
            {
                strWhere = strWhere + " AND ISGD='" + strISGD.FilterSpecial() + "'";
            }


            string pdfields = context.Request("pdfields") ?? "";
            if (pdfields != "")
            {
                ExtendModes = ExtendModes.Where(d => d.TableFiledColumn == pdfields).ToList();
            }
            if (ExtendModes.Count > 0)
            {
                string strTempSQL = new Yan_WF_PDB().GetDTHZL(ExtendModes.Select(D => D.TableFiledColumn).ToList().ListTOString(','), pdid.ToString());
                string strSQL = strTempSQL + " WHERE CRDATE BETWEEN '" + strSDate + " 01:01:01'  AND '" + strEDate + " 23:59:59' " + strWhere;
                DataTable dt = new Yan_WF_PDB().GetDTByCommand(strSQL);
                msg.Result = dt;
                msg.Result1 = ExtendModes;
            }

        }




        /// <summary>
        /// 表单监控数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETBDJKDATA(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            string iscomplate = context.Request("iscomplate") ?? ""; //判断是否有未审核的单子

            string strSDate = context.Request("sdate") ?? DateTime.Now.AddYears(-20).ToString("yyyy-MM-dd");
            string strEDate = context.Request("edate") ?? DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");

            string strWhere = "";
            if (P1 != "")
            {
                int pdid = 0;
                int.TryParse(P1, out pdid);
                strWhere = "AND  Yan_WF_PI.PDID='" + pdid + "'";
            }
            if (P2 == "1")
            {
                strWhere = strWhere + "AND  Yan_WF_PI.CRUser='" + UserInfo.User.UserName + "'";
            }
            if (iscomplate != "")
            {
                strWhere = strWhere + "AND  Yan_WF_PI.isComplete!='" + iscomplate + "'";
            }
            string strSQL = " SELECT Yan_WF_PI.ID,Yan_WF_PI.BranchName,Yan_WF_PI.CRDate,Yan_WF_PI.CRUserName,Yan_WF_PI.isComplete, Yan_WF_PI.IsCanceled,Yan_WF_PD.ProcessName,Yan_WF_PD.ProcessClass,Yan_WF_PD.ProcessType FROM  Yan_WF_PI  INNER JOIN Yan_WF_PD ON Yan_WF_PI.PDID =Yan_WF_PD.ID  WHERE 1=1  " + strWhere + " AND Yan_WF_PI.CRDATE BETWEEN '" + strSDate + " 01:01:01'  AND '" + strEDate + " 23:59:59' ";
            DataTable dt = new Yan_WF_PIB().GetDTByCommand(strSQL);
            dt.Columns.Add("StatusName");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int pid = int.Parse(dt.Rows[i]["ID"].ToString());
                string strStatusName = "正在审批";
                if (dt.Rows[i]["isComplete"].ToString() == "Y")
                {
                    strStatusName = "已审批";
                }
                if (dt.Rows[i]["IsCanceled"].ToString() == "Y")
                {
                    strStatusName = "已退回";
                }
                if (dt.Rows[i]["ProcessType"].ToString() == "-1")
                {
                    strStatusName = "无流程数据";
                }
                dt.Rows[i]["StatusName"] = strStatusName;
            }
            msg.Result = dt;

        }

        #endregion


        #region 表单设计
        public void GETFORMFILEDS(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {


            var PDS = new Yan_WF_PDB().GetEntities(D => D.ComId == UserInfo.User.ComId);

            JArray arrs = new JArray();

            foreach (var item in PDS)
            {
                List<JH_Auth_ExtendMode> ExtendModes = new List<JH_Auth_ExtendMode>();
                ExtendModes = new JH_Auth_ExtendModeB().GetEntities(D => D.ComId == UserInfo.User.ComId && D.PDID == item.ID).ToList();
                JObject obj = JObject.FromObject(new
                {
                    value = item.ID,
                    label = item.ProcessName,
                    children =
                        from p in ExtendModes
                        select new
                        {
                            value = p.TableFiledColumn,
                            label = p.TableFiledName,

                        }
                });
                arrs.Add(obj);
            }
            msg.Result = arrs;

        }

        /// <summary>
        /// 根据表解析数据字段
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETFIELDDATAFORM(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            DBFactory db = new BI_DB_SourceB().GetDB(0);
            DataTable dt = db.GetDBClient().SqlQueryable<Object>(CommonHelp.Filter("SELECT  * FROM " + P1)).ToDataTablePage(1, 1);

            dt.Columns.Remove("CRUser");
            dt.Columns.Remove("ComID");
            dt.Columns.Remove("intProcessStanceid");
            dt.Columns.Remove("CRDate");
            if (dt.Columns.Contains("RowIndex"))
            {
                dt.Columns.Remove("RowIndex");
            }
            //if (dt.Columns.Contains("DCode"))
            //{
            //    dt.Columns.Remove("DCode");
            //}
            //if (dt.Columns.Contains("DName"))
            //{
            //    dt.Columns.Remove("DName");
            //}
            if (dt.Columns.Contains("CRUserName"))
            {
                dt.Columns.Remove("CRUserName");
            }
            List<BI_DB_Dim> ListDIM = new BI_DB_SetB().getCType(dt);
            msg.Result = ListDIM;

        }

        /// <summary>
        /// 获取选择得json数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETSELUSERJSON(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            DataTable dtru = new Yan_WF_PIB().GetDTByCommand("SELECT qxdj as id, djmc as label,'0' as lev FROM DJLB");
            dtru.Columns.Add("children", Type.GetType("System.Object"));
            for (int i = 0; i < dtru.Rows.Count; i++)
            {
                DataTable dtdjuser = new Yan_WF_PIB().GetDTByCommand("SELECT YHDM as id,YHXM,xbdm.xbmc,'1' as lev from  YHDJ INNER  JOIN jsdm ON YHDJ.YHDM=jsdm.jsdm  INNER  JOIN xbdm ON jsdm.xbdm=xbdm.xbdm  WHERE QXDJ='" + dtru.Rows[i]["id"].ToString() + "'");
                dtdjuser.Columns.Add("label", Type.GetType("System.Object"));
                for (int m = 0; m < dtdjuser.Rows.Count; m++)
                {
                    dtdjuser.Rows[m]["label"] = "[" + dtdjuser.Rows[m]["xbmc"].ToString().Trim() + "]" + dtdjuser.Rows[m]["YHXM"].ToString().Trim();
                }
                dtru.Rows[i]["children"] = dtdjuser;
            }
            msg.Result = dtru;


            DataTable dtbu = new Yan_WF_PIB().GetDTByCommand("SELECT xbdm as id,xbmc as label,'0' as lev FROM xbdm where xbdm is not NULL");
            dtbu.Columns.Add("children", Type.GetType("System.Object"));
            for (int i = 0; i < dtbu.Rows.Count; i++)
            {
                DataTable dtxbuser = new Yan_WF_PIB().GetDTByCommand("SELECT jsdm as id,jsmc  as label,'1' as lev from  jsdm  where xbdm='" + dtbu.Rows[i]["id"].ToString() + "'");
                dtbu.Rows[i]["children"] = dtxbuser;
            }
            msg.Result1 = dtbu;

        }



        /// <summary>
        /// 获取FORM组件数据接口
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETYBDATA(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            try
            {
                msg.DataLength = 0;
                JObject wigdata = JObject.Parse(P1);



                string datatype = (string)wigdata["datatype"];//数据来源类型0:SQL,1:API
                if (datatype == "0")//SQL取数据
                {
                    string strWigdetType = (string)wigdata["wigdetype"];
                    string strDateSetName = (string)wigdata["datasetname"];
                    int sid = 0;
                    string dsql = "";
                    if (!strDateSetName.Contains("qj_"))
                    {
                        //看是否包含qj_，不包含就是数据集
                        BI_DB_Set DS = new BI_DB_SetB().GetEntities(d => d.Name == strDateSetName).FirstOrDefault();
                        sid = DS.SID.Value;
                        dsql = DS.DSQL;
                    }
                    else
                    {
                        BI_DB_Table DS = new BI_DB_TableB().GetEntities(d => d.TableName == strDateSetName).FirstOrDefault();
                        sid = DS.DSID;
                        dsql = "select * from " + DS.TableName;
                    }
                    JObject orderdata = (JObject)wigdata["dataorder"];

                    string ordersql = "";
                    string strPageCount = context.Request("pagecount") ?? "10";
                    string strWhere = " 1=1 ";
                    DBFactory db = new BI_DB_SourceB().GetDB(sid);
                    if (strWigdetType == "dwig")
                    {
                        JArray wdlist = (JArray)wigdata["wdlist"];


                        string strWD = "";
                        string strWDGroup = "";//处理MYSQL GROUP别名问题
                        foreach (JObject item in wdlist)
                        {
                            string strWDType = (string)item["coltype"];
                            string strWDColumCode = (string)item["colid"];
                            strWD = strWD + strWDColumCode + ",";
                            strWDGroup = strWDGroup + strWDColumCode + ",";
                            //获取维度字段筛选条件
                            JArray querylist = (JArray)item["querydata"];
                            foreach (JObject queryitem in querylist)
                            {
                                string strcal = (string)queryitem["cal"];
                                string strglval = (string)queryitem["glval"];
                                if (!string.IsNullOrEmpty(strglval))
                                {
                                    switch (strcal)
                                    {
                                        case "0": strWhere += " and " + strWDColumCode + " ='" + strglval + "'"; break;
                                        case "1": strWhere += " and " + strWDColumCode + " <'" + strglval + "'"; break;
                                        case "2": strWhere += " and " + strWDColumCode + " >'" + strglval + "'"; break;
                                        case "3": strWhere += " and " + strWDColumCode + " !='" + strglval + "'"; break;
                                        case "4": strWhere += " and " + strWDColumCode + "  LIKE  '%" + strglval.ToFormatLike() + "%'"; break;
                                        case "5": strWhere += " and " + strWDColumCode + "  BETWEEN '" + strglval.Split(',')[0] + " 00:00:00' AND '" + strglval.Split(',')[1] + " 00:00:00 '"; break;
                                        case "6": strWhere += " and " + strWDColumCode + "  IN  ('" + strglval.ToFormatLike() + "')"; break;

                                    }
                                }
                            }
                            //处理排序
                            if (orderdata != null && (string)orderdata["prop"].ToString() == strWDColumCode)
                            {
                                ordersql = strWDColumCode + " " + (string)orderdata["order"].ToString();
                            }

                        }
                        strWD = strWD.TrimEnd(',');
                        strWDGroup = strWDGroup.TrimEnd(',');
                        int pageNo = int.Parse(context.Request("pageNo") ?? "1");
                        int pageSize = int.Parse(context.Request("pageSize") ?? "0");
                        int recordTotal = 0;
                        string strRSQL = "";
                        DataTable dt = db.GetYBData(dsql, strWD, "", strPageCount, strWhere, ordersql, pageNo, pageSize, strWDGroup, "", ref recordTotal, ref strRSQL);
                        if (dt.Rows.Count > 8000)
                        {
                            //msg.ErrorMsg = "返回数据量太大,超过8000,服务器只返回前8000条数据";
                            dt = dt.SplitDataTable(1, 8000);
                        }
                        msg.Result = dt;
                        msg.DataLength = recordTotal;
                        msg.Result1 = strRSQL;
                    }
                }
                else if (datatype == "3")//存储过程
                {

                    List<SugarParameter> ListP = new List<SugarParameter>();
                    string strProname = (string)wigdata["proname"];
                    JArray prlist = (JArray)wigdata["proqdata"];
                    foreach (var item in prlist)
                    {
                        string pname = (string)item["pname"];
                        string pvalue = (string)item["pvalue"];
                        ListP.Add(new SugarParameter(pname, pvalue));
                    }

                    DBFactory dbccgc = new BI_DB_SourceB().GetDB(1);
                    DataTable dt = dbccgc.GetDBClient().Ado.UseStoredProcedure().GetDataTable(strProname, ListP);
                    msg.Result = dt;
                }
                else
                {

                    string strAPIUrl = (string)wigdata["apiurl"];
                    JArray prlist = (JArray)wigdata["proqdata"];
                    string pr = "?1=1";
                    foreach (var item in prlist)
                    {
                        string pname = (string)item["pname"];
                        string pvalue = (string)item["pvalue"];
                        pr = pr + "&" + pname + "=" + pvalue;
                    }
                    string str = CommonHelp.HttpGet(strAPIUrl.Replace("//", "/").Replace(":/", "://") + pr);
                    msg.Result = str;
                }

            }
            catch (Exception ex)
            {
                msg.ErrorMsg = "获取数据错误";
            }

        }



        public void INITIMPORTDATA(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            int pdid = 0;
            int.TryParse(P1, out pdid);
            DataTable dt = new JH_Auth_ExtendDataB().GetEntities(d => d.DataID.ToString() == P1).Select(f => new
            {
                f.ExFiledName,
                f.ExFiledColumn,
                f.ExtendDataValue
            }).ToDataTable();
            msg.Result = dt;
        }
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void SAVEIMPORTDATA(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {

            DBFactory db = new BI_DB_SourceB().GetDB(0);

            DataTable savedata = new DataTable();
            savedata = JsonConvert.DeserializeObject<DataTable>(P1);

            JObject prodata = (JObject)JsonConvert.DeserializeObject(P2);

            string tablename = (string)prodata["导入物理表名"];
            JArray procoldata = (JArray)JsonConvert.DeserializeObject((string)prodata["导入字段"]);
            savedata.Columns.Add("导入结果");
            string strIDS = "";
            for (int i = 0; i < savedata.Rows.Count; i++)
            {
                try
                {
                    var dt = new Dictionary<string, object>();
                    foreach (JObject pro in procoldata)
                    {
                        string filed = (string)pro["col68626"];

                        if ((string)pro["col81308"] != "")
                        {
                            //默认值
                            dt.Add(filed, (string)pro["col81308"]);

                        }
                        else
                        {
                            int index = int.Parse(pro["col28015"].ToString());
                            //string bz = (string)pro["col23902"];
                            dt.Add(filed, savedata.Rows[i][index].ToString());
                        }


                    }
                    int id = db.InserData(dt, tablename);
                    strIDS = strIDS + id + ",";
                    savedata.Rows[i]["导入结果"] = "导入成功";
                }
                catch (Exception ex)
                {
                    savedata.Rows[i]["导入结果"] = "导入失败" + ex.Message.ToString();
                }
            }
            if (strIDS.Trim(',') != "")
            {
                JArray gldata = (JArray)JsonConvert.DeserializeObject((string)prodata["关联更新"]);
                foreach (JObject pro in gldata)
                {
                    string upfiled = (string)pro["col56518"];
                    string gltable = (string)pro["col48753"];
                    string gltj = (string)pro["col21691"];
                    string strUPSQL = "   UPDATE " + tablename + " SET  " + upfiled + " FROM " + tablename + " INNER JOIN " + gltable + "  ON  " + gltj + " WHERE  " + tablename + ".idn in (" + strIDS.Trim(',') + ")";
                    new JH_Auth_ExtendDataB().ExsSclarSql(strUPSQL);

                }
            }


            msg.Result = savedata;


        }

        #endregion


    }
}


